package com.aynu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.aynu.common.to.es.SKUEsModel;
import com.aynu.gulimall.search.config.ElasticSearchConfig;
import com.aynu.gulimall.search.constant.EsConstant;
import com.aynu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mj
 * @version 1.0
 * @date 2021/3/8 10:09
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SKUEsModel> skuEsModels) throws IOException {
        //保存到es
        //1、给es中建立索引
        //2、es保存数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SKUEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String skuModelStr = JSON.toJSONString(skuEsModel);
            indexRequest.source(skuModelStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //获取返回结果
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        List<String> skuIds = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        if (b){
            log.error("商品上架错误,skuId: {}",skuIds);
            return true;
        }else{
            return false;
        }
    }
}
